//
//  KSStartPickingGoodsViewController.swift
//  Supermarket
//
//  Created by liuxm on 2017/9/26.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit

@objc protocol KSCompleteOrderPickingDelegate {
    @objc optional func completeOrdePicking()
    @objc optional func completeSortOut()
}

/// 开始拣货
class KSStartPickingGoodsViewController: KSBaseViewController,ViewChooseCallBackDelegate,KSChooseGoodsNumberDelegate {
    
    /// 订单号
    @IBOutlet weak var orderNoLabel: UILabel!
    /// 选择订单
    @IBOutlet weak var orderNoBtn: UIButton!
    /// 订单信息
    @IBOutlet weak var tableView: UITableView!
    weak var delegate: KSCompleteOrderPickingDelegate?
    var pickingId: String = "0"
    var orderArray: [KSStorageFjDetailListDataModel] = []
    var goodsArray: [KSStorageFjDetailListGoodsModel] = []
    var viewControllerClass: String = ""
    var orderPicking: [[String : Any]] = []
    private var codeArray: [String] = []
    private let chooseView = KSChooseCodeView()
    @IBOutlet weak var leftBtn: UIButton!
    var selectrow = 0
    /// 扫描
    fileprivate lazy var rightBtn: UIButton = {
        let rightBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        rightBtn.setBackgroundImage(UIImage.init(named: "Common_Scan"), for: .normal)
        rightBtn.setTitleColor(UIColor.black, for: UIControlState.normal)
        rightBtn.addTarget(self, action: #selector(KSStartPickingGoodsViewController.scanClick), for: UIControlEvents.touchUpInside)
        rightBtn.titleLabel?.font = KSMacro.FontBySize(size: 15)
        return rightBtn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "开始拣货"
        
        let rightButtonItem = UIBarButtonItem(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightButtonItem
        
        self.orderNoBtn.setIconInRightWithSpacing(spacing: 3)
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        let nib = UINib(nibName: "KSPickingGoodsTableViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "KSPickingGoodsTableViewCell")
        
        chooseView.delegate = self
        self.view.addSubview(chooseView)
        chooseView.snp.makeConstraints { (make) in
            make.top.equalTo(100)
            make.left.right.bottom.equalTo(0)
        }
        
        if viewControllerClass == "KSStartSortGoodsLoadedViewController" {
            goodsArray = orderArray[selectrow].order_goods!
            for i in 0...orderArray.count - 1 {
                let model = orderArray[i]
                codeArray.append(model.order_number!)
            }
        } else {
            self.leftBtn.setTitle("放弃拣货", for: .normal)
            self.leftBtn.backgroundColor = UIColor.colorWithHexString(hex: "#BEBFC0")
            self.requestData()
        }
    }
    
    private func requestData() {
        self.request.requestIosStorageJhorderdetail(jhorderId: pickingId)
    }
    
    override func requestSuccess(result: String, apiType: KSApiType) {
        super.requestSuccess(result: result, apiType: apiType)
        let model = KSStorageFjDetailListModel.deserialize(from: result)
        orderArray = (model?.data)!
        goodsArray = (orderArray.first?.order_goods)!
        for i in 0...orderArray.count - 1 {
            let model = orderArray[i]
            codeArray.append(model.order_number!)
        }
        tableView.reloadData()
    }
    
    func viewChooseCallBack(selectRow: NSInteger) {
        self.orderNoBtn.isSelected = false
        selectrow = selectRow
        goodsArray = orderArray[selectrow].order_goods!
        tableView.reloadData()
    }

    func chooseGoodsNumber(num: String, row: NSInteger) {
        let model: KSStorageFjDetailListGoodsModel = goodsArray[row]
        let pickingArray: [String : Any] = ["goods_name" : model.goods_name,"dividing_num" : "","goods_id" : "","good_sku_relation_id" : "","unit" : "","bar_code" : "","price" :
            "","sku_details" : ["name" : "","value" : ""]]
        
    }
    
    func hintMessage(msg: String) {
        self.progressHUD.showMessage(text: msg)
    }
    
    // 订单切换
    @IBAction func orderNoBtnClick(_ sender: Any) {
        self.orderNoBtn.isSelected = !self.orderNoBtn.isSelected
        if self.orderNoBtn.isSelected {
            if chooseView.dataArray.count > 0 {
                chooseView.isHidden = false
            } else {
                chooseView.dataArray = codeArray
                chooseView.setViewALLtypeUI(width: KSConstants.kScreenWidth)
            }
        } else {
            chooseView.isHidden = true
        }
    }
    
    /// 扫描
    @objc private func scanClick() {
        
    }
    
    @IBAction func lefBtnEvent(_ sender: Any) {
        if viewControllerClass == "KSStartSortGoodsLoadedViewController" {
            
        } else {
            self.request.requestIosOrderDiscardGain(orderIds: [codeArray[selectrow]])
        }
    }
    
    // 完成拣货
    @IBAction func completeBtnClick(_ sender: Any) {
        if viewControllerClass == "KSStartSortGoodsLoadedViewController" {
            self.delegate?.completeSortOut?()
        } else {
           self.delegate?.completeOrdePicking?()
        }
    }
}

extension KSStartPickingGoodsViewController: UITableViewDelegate, UITableViewDataSource {
    
    // UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return goodsArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    
    // UITableViewDelegate
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 210
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KSPickingGoodsTableViewCell", for: indexPath) as! KSPickingGoodsTableViewCell
        cell.setDataWithModel(model: goodsArray[indexPath.row],row: indexPath.row)
        cell.delegate = self
        return cell
    }
    
}
